package multidraw.model.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.server.Unreferenced;

import multidraw.model.commands.LeaveSessionCommand;

public class CanvasConnectionImpl extends UnicastRemoteObject implements CanvasConnection, Unreferenced {
	CanvasServer canvasServer;
	String name;
	public CanvasConnectionImpl(CanvasServer server) throws RemoteException {
		super();
		this.canvasServer = server;
	}

	@Override
	public void unreferenced() {
		// TODO Auto-generated method stub
		System.out.println("Client: " + name + " crashed.");
		
		// We don't need to check if this clientInfo belong to this
		// canvas connection, because the server only allow you to login
		// if and only if the previous client info has been remove.
		ClientInfo clientInfo = canvasServer.getClientInfo(name);
		//try to ping, if ok, then fine, otherwise notify the server
		if ((clientInfo != null)) {
			if (clientInfo.sessionID != null) {			
				LeaveSessionCommand cmd = new LeaveSessionCommand(name, clientInfo.sessionID);
				try {
					canvasServer.applyCommand(cmd);
				} catch (RemoteException e) {
					System.out.println(e);
				}
			}
			canvasServer.removeClient(name);
		}
	}

	@Override
	public void setName(String name) throws RemoteException {
		// TODO Auto-generated method stub
		this.name = name;
	}
}
